//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { remove_app as remove_user_app, set_top as set_user_app_top } from "@/api/user_app";
import { Button, Card, Popover, Modal, message, Space, List, Empty } from "antd";
import { EditOutlined, ExportOutlined, MoreOutlined } from "@ant-design/icons";
import defaultIcon from '@/assets/allIcon/app-default-icon.png';
import { useStores } from "@/hooks";
import { GLOBAL_APPSTORE_FS_ID } from '@/api/fs';
import AsyncImage from "@/components/AsyncImage";
import { APP_TYPE_UNKWOWN, type AppInfo } from "@/api/appstore";
import { remove_server, type UserServerInfo } from '@/api/user_server';
import EditServModal from "./userserv/EditServModal";
import { platform } from "@tauri-apps/api/os";
import { ReadOnlyEditor } from "@/components/Editor";
import { request } from "@/utils/request";

interface UserAppItemProps {
    appInfo: AppInfo;
    firstApp: boolean;
    userServerList?: UserServerInfo[] | null;
    extraInfoName?: string;
    extraInfo?: string;
    onRemove?: () => void;
    onSetTop?: () => void;
    onChangeUserServer?: () => void;
}


const UserAppItem: React.FC<UserAppItemProps> = (props) => {
    const projectStore = useStores("projectStore");
    const appStore = useStores("appStore");
    const userStore = useStores("userStore");

    const [showRemoveModal, setShowRemoveModal] = useState(false);
    const [showAddServerModal, setShowAddServerModal] = useState(false);
    const [editServerInfo, setEditServerInfo] = useState<UserServerInfo | null>(null);
    const [removeServerInfo, setRemoveServerInfo] = useState<UserServerInfo | null>(null);

    const [isOsWindows, setIsOsWindows] = useState<boolean | null>(null);

    const getIconUrl = (fileId: string) => {
        if (fileId == "") {
            return "";
        }
        if (isOsWindows) {
            return `https://fs.localhost/${GLOBAL_APPSTORE_FS_ID}/${fileId}/icon.png`;
        } else {
            return `fs://localhost/${GLOBAL_APPSTORE_FS_ID}/${fileId}/icon.png`;
        }
    };

    const removeApp = async () => {
        if (props.onRemove == undefined) {
            return;
        }
        await request(remove_user_app({
            session_id: userStore.sessionId,
            app_id: props.appInfo.app_id,
        }));
        setShowRemoveModal(false);
        message.info("卸载应用成功");
        props.onRemove();
    }

    const removeServer = async () => {
        if (removeServerInfo == null) {
            return;
        }
        await remove_server(removeServerInfo.id);
        if (props.onChangeUserServer != undefined) {
            props.onChangeUserServer();
        }
        setRemoveServerInfo(null);
        message.info("删除服务器成功");
    };

    useEffect(() => {
        platform().then((platName: string) => {
            if (platName.includes("win32")) {
                setIsOsWindows(true);
            } else {
                setIsOsWindows(false);
            }
        });
    }, []);

    return (
        <Card title={<a style={{ fontSize: "14px", fontWeight: 600 }}
            onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                appStore.openMinAppParam = {
                    minAppId: props.appInfo.app_id,
                    extraInfoName: props.extraInfoName ?? '""',
                    extraInfo: props.extraInfo ?? '""',
                };
            }}>{props.appInfo.base_info.app_name}&nbsp;<ExportOutlined /></a>} bordered
            bodyStyle={{ height: "120px" }}
            headStyle={{ backgroundColor: "#eee" }}
            style={{ boxShadow: "10px 10px 10px 0px #777" }}
            extra={
                <Space>
                    {Array.isArray(props.userServerList) && props.appInfo.base_info.app_type != APP_TYPE_UNKWOWN && (
                        <Button type="primary" style={{ height: "20px", lineHeight: 1, borderRadius: "6px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowAddServerModal(true);
                        }}>增加服务器</Button>
                    )}
                    {(props.onRemove != undefined || (props.firstApp == false && props.onSetTop != undefined)) && (
                        <Popover content={
                            <Space direction="vertical">
                                {props.firstApp == false && props.onSetTop != undefined && (
                                    <Button type="link" onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        request(set_user_app_top({
                                            session_id: userStore.sessionId,
                                            app_id: props.appInfo.app_id,
                                        })).then(() => {
                                            if (props.onSetTop != undefined) {
                                                props.onSetTop();
                                            }
                                        });
                                    }}>置顶</Button>
                                )}
                                {props.onRemove != undefined && (
                                    <Button type="link" danger onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setShowRemoveModal(true);
                                    }}>卸载</Button>
                                )}
                            </Space>
                        }
                            trigger="click" placement="bottom">
                            <MoreOutlined />
                        </Popover>
                    )}
                </Space>
            }>
            <div style={{ display: "flex" }}>
                {isOsWindows != null && (
                    <AsyncImage
                        style={{ width: "80px", cursor: "pointer" }}
                        src={getIconUrl(props.appInfo.base_info.icon_file_id)}
                        preview={false}
                        fallback={defaultIcon}
                        onClick={(e) => {
                            e.stopPropagation();
                            e.preventDefault();
                            appStore.openMinAppParam = {
                                minAppId: props.appInfo.app_id,
                                extraInfoName: props.extraInfoName ?? '""',
                                extraInfo: props.extraInfo ?? '""',
                            };
                        }}
                        useRawImg={false}
                    />
                )}
                {Array.isArray(props.userServerList) == true && props.appInfo.base_info.app_type != APP_TYPE_UNKWOWN && (
                    <div style={{ width: "200px", marginLeft: "10px", paddingLeft: "10px", height: "100px", overflowY: "scroll", paddingRight: "10px", borderLeft: "1px solid #e4e4e8" }}>
                        {(props.userServerList ?? []).filter(item => item.server_type == props.appInfo.base_info.app_type).length == 0 && (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: "10px 0px" }} description="暂无服务器" />
                        )}
                        {(props.userServerList ?? []).filter(item => item.server_type == props.appInfo.base_info.app_type).length > 0 && (
                            <List rowKey="id" dataSource={(props.userServerList ?? []).filter(item => item.server_type == props.appInfo.base_info.app_type)}
                                renderItem={serverItem => (
                                    <List.Item extra={
                                        <Space>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setEditServerInfo(serverItem);
                                                }} icon={<EditOutlined />} />
                                            <Popover trigger="click" placement="bottom" content={
                                                <Space direction="vertical">
                                                    <Button type="link" danger onClick={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        setRemoveServerInfo(serverItem);
                                                    }}>删除</Button>
                                                </Space>
                                            }>
                                                <MoreOutlined />
                                            </Popover>
                                        </Space>
                                    }>
                                        <a style={{ width: "100px", overflow: "hidden", textAlign: "left", textOverflow: "ellipsis", whiteSpace: "nowrap" }} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            appStore.openMinAppParam = {
                                                minAppId: props.appInfo.app_id,
                                                extraInfoName: JSON.stringify(serverItem.name),
                                                extraInfo: JSON.stringify(serverItem.server_info),
                                            };
                                        }}>{serverItem.name}{(serverItem.project_id ?? "") != "" && `(${projectStore.getProject(serverItem.project_id ?? "")?.basic_info.project_name ?? ""})`}</a>
                                    </List.Item>
                                )} />
                        )}
                    </div>
                )}
                {Array.isArray(props.userServerList) == true && props.appInfo.base_info.app_type == APP_TYPE_UNKWOWN && (
                    <div style={{ width: "200px", marginLeft: "10px", paddingLeft: "10px", height: "100px", overflowY: "scroll", paddingRight: "10px", borderLeft: "1px solid #e4e4e8" }}>
                        <ReadOnlyEditor content={props.appInfo.base_info.app_desc} />
                    </div>
                )}
                {Array.isArray(props.userServerList) == false && (
                    <div style={{ width: "200px", marginLeft: "10px", paddingLeft: "10px", height: "100px", overflowY: "scroll", paddingRight: "10px", borderLeft: "1px solid #e4e4e8" }}>
                        <ReadOnlyEditor content={props.appInfo.base_info.app_desc} />
                    </div>
                )}
            </div>
            {showRemoveModal == true && (
                <Modal open title="卸载应用" mask={false}
                    okButtonProps={{ danger: true }}
                    okText="卸载应用"
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowRemoveModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeApp();
                    }}>
                    是否卸载应用&nbsp;{props.appInfo.base_info.app_name}&nbsp;?
                </Modal>
            )}
            {showAddServerModal == true && (
                <EditServModal appType={props.appInfo.base_info.app_type} onCancel={() => setShowAddServerModal(false)} onOk={() => {
                    setShowAddServerModal(false);
                    if (props.onChangeUserServer != undefined) {
                        props.onChangeUserServer();
                    }
                }} />
            )}
            {editServerInfo != null && (
                <EditServModal serverInfo={editServerInfo} onCancel={() => setEditServerInfo(null)} onOk={() => {
                    setEditServerInfo(null);
                    if (props.onChangeUserServer != undefined) {
                        props.onChangeUserServer();
                    }
                }} />
            )}
            {removeServerInfo != null && (
                <Modal open title="删除服务器" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveServerInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeServer();
                    }}>
                    是否删除服务器&nbsp;{removeServerInfo.name}&nbsp;?
                </Modal>
            )}
        </Card>
    );
};

export default observer(UserAppItem);